package people.paper.tv.activity.home;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.umeng.analytics.MobclickAgent;

import people.paper.tv.BaseApplication;
import people.paper.tv.R;
import people.paper.tv.activity.BaseActivity;
import people.paper.tv.activity.home.modual.rmrb.RMRBFragment;
import people.paper.tv.activity.home.modual.rmrb.view.impl.RMRBViewImpl;
import people.paper.tv.activity.home.modual.sptt.SPTTFragment;
import people.paper.tv.activity.home.modual.ydtj.YDTJFragment;
import people.paper.tv.activity.home.modual.ywyl.YWYLFragment;
import people.paper.tv.activity.home.view.HomeView;
import people.paper.tv.activity.home.view.IFragementCallback;
import people.paper.tv.activity.home.view.impl.HomeViewImpl;
import people.paper.tv.speech.SpeechManager;
import people.paper.tv.utils.monitor.Monitor;

public class HomeActivity extends BaseActivity implements IFragementCallback {
    public static final int RMRB_INDEX = 0;
    public static final int YWYL_INDEX = 1;
    public static final int YDTJ_INDEX = 2;
    public static final int SPTT_INDEX = 3;

    public static final void start(Context context, int index) {
        Intent intent = new Intent();
        intent.setClass(context, HomeActivity.class);
        intent.putExtra(INTENT_EXTRA_INDEX, String.valueOf(index));
        if (!(context instanceof Activity))
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private static final String INTENT_EXTRA_INDEX = "show.index";
    private static final int DEFAULT_INDEX = 0;
    private final HomeFragment[] fragments = new HomeFragment[]{
            new RMRBFragment(),
            new YWYLFragment(),
            new YDTJFragment(),
            new SPTTFragment()};

    private HomeView homeView;
    HomeFragment fromFragment = null, toFragment = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        homeView = new HomeViewImpl(this);
        setContentView(homeView.getView());
        homeView.setFragementCallback(this);
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        for (int i = 0; i < fragments.length; i++) {
            HomeFragment fragment = fragments[i];
            String tagName = fragment.NAME;
            fragment.setHomeFragmentManager(homeFragmentManager);
            fragment.setHomeView(homeView);
            fragment.setTabId(i);
            ft.add(homeView.getFragmentId(), fragment, tagName).hide(fragment);
        }
        ft.commit();
        show();
//        getFragmentManager().beginTransaction().show(fragments[0]).commit();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        show();

//        switchFragment(fragments[2], fragments[0], false);
    }

    private void show() {
        int showIndex = DEFAULT_INDEX;
        Intent intent = getIntent();
        if (intent != null) {
            String _index = intent.getStringExtra(INTENT_EXTRA_INDEX);
            try {
                showIndex = Integer.valueOf(_index);
            } catch (Exception e) {
            }
        }
        if (showIndex < 0 || showIndex > (fragments.length - 1))
            showIndex = DEFAULT_INDEX;
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        fromFragment = toFragment;
        HomeFragment to = fragments[showIndex];
        toFragment = to;
        Log.i("FFF", "presenter "+fromFragment+"; "+to.NAME);
        if(fromFragment != null && fromFragment.NAME.equals(to.NAME)){

        }else if(fromFragment != null){
            if(fromFragment.getTabId() > toFragment.getTabId())
                switchFragment(fromFragment, toFragment, false);
            else
                switchFragment(fromFragment, toFragment, true);
        }else {
            for (int i = 0; i < fragments.length; i++) {
                HomeFragment fragment = fragments[i];
                if (i == showIndex) {
                    ft.show(fragment);
                }else {
                    ft.hide(fragment);
                }
                Log.i("FFF", "presenter "+i+"; "+to.NAME);
            }
            ft.commit();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        SpeechManager.create(this);
    }

    @Override
    protected void onStop() {
        SpeechManager.destroy();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApplication.killSelf();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("sptt","HomeActivity onResume");
        MobclickAgent.onResume(this);
        Monitor.end(this, "target1");
    }

    @Override
    protected void onPause() {
        Log.d("sptt","HomeActivity onPause");
        MobclickAgent.onPause(this);
        super.onPause();
    }

    private final void switchFragment(HomeFragment from, HomeFragment to, boolean leftOut) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        if (leftOut)
            ft.setCustomAnimations(
                    R.animator.fragment_slide_right_in, R.animator.fragment_slide_left_out);
        else
            ft.setCustomAnimations(
                    R.animator.fragment_slide_left_in, R.animator.fragment_slide_right_out);
        if (!to.isAdded()) {    // 先判断是否被add过
            ft.hide(from).add(homeView.getFragmentId(), to).commit();
        } else {
            ft.hide(from).show(to).commit();
        }
        toFragment = to;
    }

    private boolean bInAnimation = false;
    private final HomeFragment.HomeFragmentManager homeFragmentManager = new HomeFragment.HomeFragmentManager() {
        private final AnimatorListenerAdapter animatorListenerAdapter = new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                synchronized (homeFragmentManager) {
                    bInAnimation = true;
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                synchronized (homeFragmentManager) {
                    bInAnimation = false;
                }
            }
        };

        @Override
        public AnimatorListenerAdapter getAnimatorListenerAdapter() {
            return animatorListenerAdapter;
        }

        private HomeFragment current;

        @Override
        public boolean prev(int index) {
            synchronized (homeFragmentManager) {
//                if (bInAnimation)
//                    return false;
                HomeFragment from = fragments[index];
                index -= 1;
                if (index < 0)
                    index = fragments.length - 1;
                HomeFragment to = fragments[index];
                switchFragment(from, to, false);
                current = to;
                return true;
            }
        }

        @Override
        public boolean next(int index) {
            synchronized (homeFragmentManager) {
//                if (bInAnimation)
//                    return false;
                HomeFragment from = fragments[index];
                index += 1;
                if (index > fragments.length - 1)
                    index = 0;
                HomeFragment to = fragments[index];
                switchFragment(from, to, true);
                current = to;
                return true;
            }
        }

        @Override
        public boolean click(int preId,int index) {
            synchronized (homeFragmentManager) {
//                if (bInAnimation)
//                    return false;
                if (preId > fragments.length - 1){
                    preId = 0;
                }else if(preId < 0){
                    preId = fragments.length - 1;
                }
                if (index > fragments.length - 1){
                    index = fragments.length - 1;
                }else if(preId < 0){
                    index = 0;
                }
                boolean is = (index>preId) ? true : false;
                HomeFragment from = fragments[preId];
                HomeFragment to = fragments[index];
                switchFragment(from, to, is);
                current = to;
                return true;
            }
        }

        @Override
        public HomeFragment getCurrentHomeFragment() {
            synchronized (homeFragmentManager) {
                return current;
            }
        }
    };

    @Override
    public boolean prev(int id) {
        if (bInAnimation)
            return false;
        homeFragmentManager.prev(id);
        return true;
    }

    @Override
    public boolean next(int id) {
        if (bInAnimation)
            return false;
        homeFragmentManager.next(id);
        return true;
    }

    @Override
    public boolean click(int preId,int id) {
        if (bInAnimation)
            return false;
        homeFragmentManager.click(preId,id);
        return true;
    }

    @Override
    public void showDataPick() {
        ((RMRBViewImpl)fragments[RMRB_INDEX].getViewImpl()).showDataPick();
    }

    @Override
    public boolean setFragmentFocus(int tabId) {
        return fragments[tabId].getViewImpl().setLayoutFocus();
    }
}
